import React, { useContext } from "react";
import { v4 } from "uuid";
import useLocalStorage from "../hook/useLocalStorage";

const BudgetsContext = React.createContext();
export const NOCLASS = "default"

export function useBudgets(){
    return useContext(BudgetsContext);
}

export const BudgetsProvider = ({children}) => {
    const [budgets, setBudgets] = useLocalStorage("budgets", []);
    const [expenses, setExpenses] = useLocalStorage("expenses", []);
    
    function getBudgetExpenses(budgetId) { 
        return expenses.filter(expense => expense.budgetId === budgetId)

    }
    
    function addExpense(description, amount, budgetId,) {
        setExpenses(prevExpenses => {
            return [...prevExpenses, {id: v4(),description, amount, budgetId}]
        })
    }
            
    function addBudget(name, max) {
        setBudgets(prevBudgets => {
            if(prevBudgets.find(budget => budget.name === name)) {
                return prevBudgets;
            }
            return [...prevBudgets, {id: v4(), name, max}]
        })

    }
        
    function deleteBudget(id) {
        
        setExpenses(prevExpenses => {
            return prevExpenses.map(expense => {
                if(expense.budgetId === id) expense.budgetId = NOCLASS;
                return expense
            })
        })
        setBudgets(prevBudgets => {
            return prevBudgets.filter(budget => budget.id !== id)
        })
        console.log(budgets)
    }
            
    function deleteExpense(id) {
        setExpenses(prevExpenses => {
            return prevExpenses.filter(expense => expense.id !== id)
        })
    }

    return(
        <BudgetsContext.Provider value={{
            budgets,
            expenses,
            getBudgetExpenses,
            addExpense,
            addBudget,
            deleteBudget,
            deleteExpense
        }}>
            {children}
        </BudgetsContext.Provider>
    )
}